2023/12/231332字符

表达式

运算符

++ a ++;  // 报错,根据优先级会先执行 a++
var a = 42;
var b = (a++);
a;  //--> 43
b;  //--> 42

() 本身并不是一个封装表达式,不会在表达式 a++ 产生副作用之后执行,即便可以,a++ 会首先返回 42,除非有表达式在 ++ 之后对 a 进行运算,否则会得到43,也就不能将43赋值给 b

var a = 42, b;
b = (a++, a);
a;  //--> 43
b;  //--> 43

var a = 42, b;
b = a++, a;
a;  //--> 43
b;  //--> 42

运算符的优先级比 = 低。所以 b = a++ ,a 其实可以理解为 (b = a++),a 。所以 b 的值是 ++ 对 a 做递增之前的是 42

if 条件

/**
 * 捕捉元音字母
 * @param {string} str 
 */
function vowels(str){
    var matches;
    if(str){
        matches = str.match(/[aeiou]/g);
        if(matches){
            return matches;
        }
    }
}
vowels('hello world');  //--> ["e", "o", "o"]

其实可以写成这样

function vowels(str){
    if(str && (matches = str.match(/[aeiou]/g))){
        return matches;
    }
}
  • 事实上JavaScript中没有 else if ,但 if 和 else 只包含单条语句时可以省略 {}
if(a){}else if(b){}else{}

if(a){}else{
    if(b){}else{}
}